<template>
  <!-- 自定义组件事件，通过@进行调用 -->
  <div class="login-page mx-auto p-3 w-330">
    <h5 class="my-4 text-center">登录到者也</h5>
    <validate-form @form-submit="onFormSubmit" ref="loginForm">
      <div class="mb-3">
        <label  class="form-label">邮箱地址</label>
        <validate-input
          type="text"
          placeholder="请输入邮箱地址"
          :rules="emailRules"
          v-model="emailVal"
        />
      </div>
      <div class="mb-3">
        <label  class="form-label">密码</label>
        <validate-input
          type="password"
          placeholder="请输入密码"
          :rules="passwordRules"
          v-model="passwordVal"
        />
        <div class="form-text">
          <router-link to="/signup">还没有账户？去注册一个新的吧！</router-link>
        </div>
      </div>
      <!-- 通过templete指定具名插槽的内容，v-slot:submit可以简写为#submit -->
      <template #submit>
        <button type="submit" class="btn btn-primary">登录</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { GlobalDataProps } from '../store'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import createMessage from '../components/createMessage'

export default defineComponent({
  name: 'Login',
  components: {
    ValidateInput,
    ValidateForm
  },
  setup () {
    const emailVal = ref('')
    const passwordVal = ref('')
    const loginForm = ref()
    const router = useRouter() // 定义路由的行为
    const store = useStore<GlobalDataProps>()
    const emailRules: RulesProp = [
      { type: 'required', message: '电子邮箱地址不能为空！' },
      { type: 'email', message: '请输入正确的电子邮箱格式！' },
      {
        type: 'range',
        min: { length: 6, message: '邮箱的长度为6-20位, 不能含有空格！' },
        max: { length: 20, message: '邮箱的长度为6-20位, 不能含有空格！' }
      }
    ]
    const passwordRules: RulesProp = [
      { type: 'required', message: '密码不能为空！' },
      { type: 'range', min: { length: 6, message: '密码至少包含6位，不能含有空格！' } }
    ]
    const onFormSubmit = (result: boolean) => {
      if (result) {
        // 登录数据校验通过，发送登录请求,登录请求时异步函数，返回Promise对象，可以调用then方法
        const payload = { email: emailVal.value, password: passwordVal.value }
        store.dispatch('loginAndFetchCurrentUser', payload).then(() => {
          createMessage('登录成功, 2秒后跳转到首页！', 'success')
          setTimeout(() => {
            // 登录成功跳转到首页
            router.push('/')
          }, 2000)
        }).catch(() => {
          loginForm.value.clearInputs()
        })
      } else {
        // 调用form表单返回的函数清空输入框
        loginForm.value.clearInputs()
      }
    }
    return {
      emailRules,
      passwordRules,
      onFormSubmit,
      loginForm,
      emailVal,
      passwordVal
    }
  }
})
</script>

<style>
.w-330 {
  max-width: 330px;
}
</style>
